import { execRemoteAPI } from "@/views/formgen/api/execRemoteAPI";
import { get, isArray } from "lodash-es";

interface Option {
  label: string;
  value: string;
  children?: Option[];
}

export function useFormOption() {
  // 是否随机选项
  const getOptions = async (config: any, isRandomOption = false) => {
    let finalOptions = config.options;
    if (config.optionsType && config.optionsType === 1) {
      try {
        if (!config.dynamicOptions.url) {
          return [];
        }
        const res = await execRemoteAPI.get<any>(config.dynamicOptions.url);
        const options = get(res, config.dynamicOptions.dataPath);
        if (options && isArray(options)) {
          finalOptions = options.map((op: any) => {
            let other: any = {};
            if (config.dynamicOptions.childrenField) {
              const processChildren = (list: any[]): Option[] => {
                return list.map((item: any) => {
                  let childrenList = get(item, config.dynamicOptions.childrenField);
                  let children: Option[] = [];
                  if (childrenList && isArray(childrenList)) {
                    // 递归处理子节点
                    children = processChildren(childrenList);
                  }
                  return {
                    value: get(item, config.dynamicOptions.valueField),
                    label: get(item, config.dynamicOptions.labelField),
                    ...(children.length > 0 ? { children } : {}) // 只有当有子节点时才添加 children 属性
                  };
                });
              };
              other.children = processChildren(get(op, config.dynamicOptions.childrenField) as any[]);
            }
            return {
              value: get(op, config.dynamicOptions.valueField),
              label: get(op, config.dynamicOptions.labelField),
              ...other
            };
          });
        }
      } catch (error) {
        console.error("Error fetching dynamic options:", error);
      }
      //  如果是字典值 从字字典接口获取
    } else if (config.optionsType && config.optionsType === 2) {
      try {
        const dictRes = await execRemoteAPI.get<any>(`/system/dict/data/type/${config.dictOptionType}`);
        finalOptions = dictRes.data.map((op: any) => ({
          value: op.dictValue,
          label: op.dictLabel
        }));
      } catch (error) {
        console.error("Error fetching dictionary options:", error);
      }
    } else if (config.optionsType && config.optionsType === 3) {
      try {
        const dictRes = await execRemoteAPI.get<any>(`/user/form/data/field/data/list`, {
          formKey: config.linkFormKey,
          formItemId: config.linkFormItemId
        });
        finalOptions = dictRes.data.map((op: any) => ({
          value: op,
          label: op
        }));
      } catch (error) {
        console.error("Error fetching dictionary options:", error);
      }
    }
    // 如果传入了随机选项 并且是开启了随机选项 避免有的页面不需要随机的时候也随机了
    if (isRandomOption && config.optionRandom) {
      // 随机选项 并且可以指定是否固定最后一项
      if (config.optionRandom && config.lastOptionNotRandom) {
        const lastOption = finalOptions.pop();
        finalOptions = finalOptions.sort(() => Math.random() - 0.5);
        finalOptions.push(lastOption);
      } else {
        finalOptions = finalOptions.sort(() => Math.random() - 0.5);
      }
      console.log(finalOptions);
    }
    return finalOptions;
  };
  return {
    getOptions
  };
}
